<template>
  <div style="padding:  0 20px">

    <div id="chart">

    </div>

  </div>


</template>

<script setup>
import {onMounted, onUnmounted, ref} from 'vue'

import * as echarts from 'echarts';
import {getStatisticsInfo} from "../../../api/client/home.js";


const props = defineProps({
  type: String,
  title: String
})

const getStat = async () => {
  const res = await getStatisticsInfo({type: props.type})
  return res.data
}


const series = []
const xData = []


const getSeries = (data) => {
  let sortedEntries = Object.entries(data).sort((a, b) => b[1] - a[1]);
  data = Object.fromEntries(sortedEntries);
  for (let domain of Object.keys(data)) {
    let val = data[domain]
    if (props.type == 3 || props.type == 4) {
      val = (val / 1024 / 1024 / 1024).toFixed(2)
    }
    let items = series.filter(item => {
      return item.name === domain
    })
    if (items.length === 0) {
      series.push({
        name: domain,
        type: 'line',
        showSymbol: false,
        data: [val]
      })
    } else {
      const item1 = items[0];
      if (item1.data.length > 1000) {
        item1.data.shift();
      }
      item1.data.push(val)
    }
  }
  if (xData.length > 1000) {
    xData.shift();
  }
  xData.push(new Date().toLocaleString())
}


const option = {
  title: {
    text: props.title
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      animation: false
    }
  },
  xAxis: {
    type: 'category',
    data: []
  },
  yAxis: {
    type: 'value',
    boundaryGap: [0, '100%'],
    splitLine: {
      show: false
    }
  },
  dataZoom: [       {
    type: 'slider', //滑动条
    show: true,      //开启
    yAxisIndex: [0],
    left: '93%',  //滑动条位置
    start: 1,    //初始化时，滑动条宽度开始标度
    end: 80      //初始化时，滑动条宽度结束标度
  },
    {
      type: 'inside',  //内置滑动，随鼠标滚轮展示
      yAxisIndex: [0],
      start: 1,//初始化时，滑动条宽度开始标度
      end: 80  //初始化时，滑动条宽度结束标度
    } ],
  series: []
};
let interval = null;
onMounted(function () {
  const chartDom = document.getElementById('chart');
  const myChart = echarts.init(chartDom);
  option && myChart.setOption(option);
   interval = setInterval(async function () {
    getSeries(await getStat())
    myChart.setOption({
      xAxis: {
        data: xData
      },
      series: series
    });
  }, 2000);
})
onUnmounted(()=>{
  if (interval!=null){
    clearInterval(interval)
  }
})

</script>

<style scoped>

#chart {
  width: 80vw;
  height: 80vh;
}

</style>
